package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmNewsService wmNewsService;

    /**
     * 查询所有频道
     * @return
     */
    @Override
    public ResponseResult channels() {
        return ResponseResult.okResult(list());
    }

    /**
     * 删除频道
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteChannel(Integer id) {
        // 1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.判断频道是否禁用
        WmChannel wmChannel = getById(id);
        if (wmChannel.getStatus().equals(1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"此频道未禁用，不能删除");
        }
        // 3.删除频道
        return ResponseResult.okResult(removeById(id));
    }

    /**
     * 频道名称模糊分页查询
     * @param channelDto
     * @return
     */
    @Override
    public PageResponseResult getChannelList(ChannelDto channelDto) {
        // 1.检查参数
        channelDto.checkParam();
        // 2.构建分页对象
        Page<WmChannel> page = new Page<>(channelDto.getPage(),channelDto.getSize());
        // 3.构建分页条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        // 3.1 按照频道创建时间倒叙排序
        queryWrapper.orderByDesc(WmChannel::getCreatedTime);
        // 3.2 按照频道名称模糊查询
        if (StringUtils.isNotBlank(channelDto.getName())) {
            queryWrapper.like(WmChannel::getName,channelDto.getName());
        }
        // 3.3 按照频道状态精确查找（启用：0  禁用：1）
        if (channelDto.getStatus() != null) {
            queryWrapper.eq(WmChannel::getStatus,channelDto.getStatus());
        }
        // 4.分页查询
        page = page(page, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(channelDto.getPage(),channelDto.getSize(),(int)page.getTotal());
        pageResponseResult.setData(page.getRecords());
        // 5.返回结果
        return pageResponseResult;
    }

    /**
     * 保存频道
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        // 1.检查参数
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.判断频道是否存在
        WmChannel channel = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, wmChannel.getName()));
        if (channel != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"频道已存在");
        }
        // 3.设置其他属性
        wmChannel.setCreatedTime(new Date());
        wmChannel.setIsDefault(true);
        // 4.保存频道
        save(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 修改频道
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        // 1.检查参数
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
//        // 2.判断频道是否存在
//        WmChannel channel = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, wmChannel.getName()));
//        if (channel != null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"频道已存在");
//        }
        // 如果频道被引用，则不能禁用
        if (wmChannel.getStatus().equals(0)) {
            // 3.判断频道是否被引用
            List<WmNews> wmNewsList = wmNewsService.list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId()));
            if (wmNewsList != null || wmNewsList.size() > 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该频道已被引用，不能禁用");
            }
        }


        // 4.修改频道
        updateById(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }}